package com.jinsilu.freight.ui.activity;

import static com.jinsilu.freight.ui.fragment.UnfinishedWaybillFragment.TAG_NEED_TO_REFRESH_WAYBILL;

import android.content.Intent;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.UnderlineSpan;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.BusUtils;
import com.blankj.utilcode.util.LogUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.hdgq.locationlib.entity.ShippingNoteInfo;
import com.hjq.base.BaseDialog;
import com.hjq.base.BaseFragmentAdapter;
import com.hjq.http.EasyConfig;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jinsilu.freight.R;
import com.jinsilu.freight.common.MyActivity;
import com.jinsilu.freight.common.MyFragment;
import com.jinsilu.freight.helper.ActivityStackManager;
import com.jinsilu.freight.helper.CommonHelper;
import com.jinsilu.freight.helper.DoubleClickHelper;
import com.jinsilu.freight.http.model.HttpData;
import com.jinsilu.freight.http.request.GetAppInfoApi;
import com.jinsilu.freight.http.request.GetNeedUpdateApi;
import com.jinsilu.freight.http.request.UserInfoApi;
import com.jinsilu.freight.http.response.AppInfoBean;
import com.jinsilu.freight.http.response.UserInfoBean;
import com.jinsilu.freight.other.AppConfig;
import com.jinsilu.freight.other.ForegroundService;
import com.jinsilu.freight.other.KeyboardWatcher;
import com.jinsilu.freight.other.MTLConstants;
import com.jinsilu.freight.ui.dialog.UpdateDialog;
import com.jinsilu.freight.ui.fragment.HomeFragment;
import com.jinsilu.freight.ui.fragment.MeFragment;
import com.jinsilu.freight.ui.fragment.SourceHallFragment;
import com.jinsilu.freight.ui.fragment.WaybillFragment;

import java.util.List;

/**
 * author : byd
 * time   : 2020年11月6日
 * desc   : 主页界面
 */
public final class HomeActivity extends MyActivity
        implements KeyboardWatcher.SoftKeyboardStateListener,
        BottomNavigationView.OnNavigationItemSelectedListener {

    private ViewPager mViewPager;
    private BottomNavigationView mBottomNavigationView;

    private BaseFragmentAdapter<MyFragment> mPagerAdapter;

    private HomeFragment homeFragment;
    private WaybillFragment waybillFragment;

    public static final String TAG_REFRESH_USER_DATA = "TagRefreshUserData";
    public static final String TAG_START_COUNT_DOWN = "TagStartCountDown";
    public static final String TAG_CANCEL_COUNT_DOWN = "TagCancelCountDown";

    @BusUtils.Bus(tag = TAG_START_COUNT_DOWN, sticky = true)
    public void startCountDown(List<ShippingNoteInfo> list) {
        if (list.isEmpty()) return;
        BusUtils.removeSticky(TAG_START_COUNT_DOWN);
        Intent intent = new Intent(this, ForegroundService.class);
        intent.putExtra("ShippingNoteInfo", list.get(0));
        startService(intent);
    }

    @BusUtils.Bus(tag = TAG_CANCEL_COUNT_DOWN, sticky = true)
    public void cancelCountDown() {
        BusUtils.removeSticky(TAG_CANCEL_COUNT_DOWN);
        //停止服务
        Intent intent = new Intent(this, ForegroundService.class);
        stopService(intent);
    }

    @BusUtils.Bus(tag = TAG_REFRESH_USER_DATA, sticky = true)
    public void refreshCar() {
        BusUtils.removeSticky(TAG_REFRESH_USER_DATA);
        refreshUserData();
    }

    @BusUtils.Bus(tag = TAG_NEED_TO_REFRESH_WAYBILL, sticky = true)
    public void onRefresh() {
        /*通知刷新*/
        BusUtils.removeSticky(TAG_NEED_TO_REFRESH_WAYBILL);
        goWantToPage(MTLConstants.WAYBILL_PAGE_INDEX);
    }

    @Override

    protected int getLayoutId() {
        return R.layout.home_activity;
    }

    @Override
    protected void initView() {
        mViewPager = findViewById(R.id.vp_home_pager);
        mBottomNavigationView = findViewById(R.id.bv_home_navigation);

        // 不使用图标默认变色
        mBottomNavigationView.setItemIconTintList(null);
        mBottomNavigationView.setOnNavigationItemSelectedListener(this);

        KeyboardWatcher.with(this)
                .setListener(this);
    }

    @Override
    protected void initData() {

        // 添加全局请求参数 更新 Token
        EasyConfig.getInstance()
                .addHeader("token", CommonHelper.getToken());

        mPagerAdapter = new BaseFragmentAdapter<>(this);
        mPagerAdapter.addFragment(homeFragment = HomeFragment.newInstance());
        mPagerAdapter.addFragment(waybillFragment = WaybillFragment.newInstance());
        mPagerAdapter.addFragment(SourceHallFragment.newInstance());
        mPagerAdapter.addFragment(MeFragment.newInstance());
        // 设置成懒加载模式
        mPagerAdapter.setLazyMode(true);
        mViewPager.setAdapter(mPagerAdapter);

        if (CommonHelper.isLogin())
            refreshUserData();

        // 未授权
        if (!CommonHelper.getAuthStatus()) showPrivacyDialog();

    }

    @Override
    protected void onResume() {
        super.onResume();
        getAppInfo(); // App升级
        getNeedAppUpdate(); // 是否升级至重构版本
    }

    /**
     * 展示隐私权限弹框
     */
    private void showPrivacyDialog() {
        // 自定义对话框
        BaseDialog privacyDialog = new BaseDialog.Builder(getContext())
                .setContentView(R.layout.dialog_privacy)
                .setAnimStyle(BaseDialog.ANIM_SCALE)
                .setCanceledOnTouchOutside(false)
                .setOnClickListener(R.id.btn_dialog_custom_ok, (BaseDialog.OnClickListener<Button>) (dialog, view) -> {
                    dialog.dismiss();
                    CommonHelper.saveAuthStatus(true);
                    getLocationPermission();
                })
                .setOnClickListener(R.id.btn_dialog_custom_cancel, (BaseDialog.OnClickListener<Button>) (dialog, view) -> {
                    dialog.dismiss();
                    CommonHelper.saveAuthStatus(false);
                })
                .addOnShowListener(dialog -> {
                })
                .addOnCancelListener(dialog -> {
                })
                .addOnDismissListener(dialog -> {
                })
                .setOnKeyListener((dialog, event) -> {
//                    toast("按键代码：" + event.getKeyCode());
                    return false;
                })
                .create();

        AppCompatTextView privacyContent = privacyDialog.getContentView().findViewById(R.id.tv_privacy_content);
        String content = "请您务必审慎阅读，应网络货运监管平台要求，需要在您运输过程中使用定位权限，获取您的所在位置并上传至网络货运监管平台；定位使用高德提供的定位服务，关于高德定位隐私权限可以阅读《高德地图开放平台隐私权政策》了解详细信息。如您同意，请点击“同意”开始接受我们的服务。";
        SpannableStringBuilder spannableString = new SpannableStringBuilder(content);
        int privateBeginIndex = content.indexOf("《");
        int privateEndIndex = content.indexOf("》") + 1;
        setUserPolicy(spannableString, privateBeginIndex, privateEndIndex, "privacy");
        //设置点击事件，加上这句话才有效果
        privacyContent.setMovementMethod(LinkMovementMethod.getInstance());
        //设置点击后的颜色为透明（有默认背景）
        privacyContent.setHighlightColor(getResources().getColor(R.color.transparent));
        privacyContent.setText(spannableString);
        privacyDialog.show();
    }

    public void setUserPolicy(SpannableStringBuilder spannableString, int start, int end, String type) {
        //设置部分文字点击事件
        ClickableSpan clickableSpan = new ClickableSpan() {

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                //超链接形式的下划线，false 表示不显示下划线，true表示显示下划线
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(View widget) {
                BrowserActivity.start(widget.getContext(), "https://lbs.amap.com/pages/privacy/");
            }
        };
        spannableString.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        //设置部分文字颜色
//        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#5e89ef"));

        //使用ForegroundColorSpan添加点击事件会出现冲突
        UnderlineSpan colorSpan = new UnderlineSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(Color.parseColor("#5e89ef"));//设置颜色
            }
        };
        spannableString.setSpan(colorSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    /**
     * 获取定位权限，成功后调用停止定位
     * 运单状态 1:待装货(抢完单) 2:运输中(上传装车磅单后) 3:已卸车(上传卸车磅单后) 4:装车磅单打回 5:卸车磅单打回 6:装卸车打回 7:支付中 8:已支付 9:开票中 10:已开票
     */
    private void getLocationPermission() {
        XXPermissions.with(this)
                .permission(new String[]{
                        Permission.ACCESS_FINE_LOCATION,
                        Permission.ACCESS_COARSE_LOCATION})
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {

                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                    }
                });
    }

    private void refreshUserData() {
        // 刷新用户信息
        EasyHttp.get(this)
                .api(new UserInfoApi())
                .request(new HttpCallback<HttpData<UserInfoBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<UserInfoBean> data) {
                        CommonHelper.saveObject("userInfo", data.getData());
                        if (null != homeFragment)
                            homeFragment.setUserCar();
                    }
                });
    }

    /**
     * {@link BottomNavigationView.OnNavigationItemSelectedListener}
     */

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        if (null == mViewPager) return false;
        int itemId = item.getItemId();
        if (itemId == R.id.menu_home) {
            mViewPager.setCurrentItem(0);
            return true;
        } else if (itemId == R.id.home_waybill) {
            mViewPager.setCurrentItem(1);
            return true;
        } else if (itemId == R.id.home_goods) {
            mViewPager.setCurrentItem(2);
            return true;
        } else if (itemId == R.id.home_me) {
            if (!CommonHelper.isLogin()) {
                CommonHelper.goLoin();
            } else {
                mViewPager.setCurrentItem(3);
            }
            return true;
        }
        return false;
    }

    /**
     * 跳转至想要跳转至的页面
     *
     * @param pageIndex 页面索引
     */
    public void goWantToPage(int pageIndex) {
        if (null != mBottomNavigationView) {
            mBottomNavigationView.setSelectedItemId(R.id.home_waybill);
            if (null != mViewPager) mViewPager.setCurrentItem(pageIndex);
        }
        if (null != waybillFragment)
            waybillFragment.setWaybillCurrentPage(MTLConstants.WAYBILL_UNFINISHED_PAGE_INDEX);
    }

    /**
     * {@link KeyboardWatcher.SoftKeyboardStateListener}
     */
    @Override
    public void onSoftKeyboardOpened(int keyboardHeight) {
        if (null != mBottomNavigationView)
            mBottomNavigationView.setVisibility(View.GONE);
    }

    @Override
    public void onSoftKeyboardClosed() {
        if (null != mBottomNavigationView)
            mBottomNavigationView.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 回调当前 Fragment 的 onKeyDown 方法
        if (null != mPagerAdapter) {
            if (mPagerAdapter.getShowFragment().onKeyDown(keyCode, event)) {
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (DoubleClickHelper.isOnDoubleClick()) {
            // 移动到上一个任务栈，避免侧滑引起的不良反应
            moveTaskToBack(false);
            postDelayed(() -> {

                // 进行内存优化，销毁掉所有的界面
                ActivityStackManager.getInstance().finishAllActivities();
                // 销毁进程（注意：调用此 API 可能导致当前 Activity onDestroy 方法无法正常回调）
                // System.exit(0);

            }, 300);
        } else {
            toast(R.string.home_exit_hint);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        BusUtils.register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        BusUtils.unregister(this);
    }

    @Override
    protected void onDestroy() {
        if (null != mViewPager)
            mViewPager.setAdapter(null);
        if (null != mBottomNavigationView)
            mBottomNavigationView.setOnNavigationItemSelectedListener(null);
        super.onDestroy();
    }

    @Override
    public boolean isSwipeEnable() {
        return false;
    }

    /**
     * 获取fir.im app 信息
     */
    BaseDialog updateDialog = null;

    private void getAppInfo() {
        EasyHttp.get(this)
                .api(new GetAppInfoApi())
                .request(new HttpCallback<AppInfoBean>(this) {

                    @Override
                    public void onSucceed(AppInfoBean data) {
                        // 本地的版本码和服务器的进行比较
                        if (Integer.parseInt(data.getVersion()) > AppConfig.getVersionCode()) {
                            if (null == updateDialog) {
                                updateDialog = new UpdateDialog.Builder(HomeActivity.this)
                                        // 版本名
                                        .setVersionName(data.getVersionShort())
                                        // 是否强制更新
                                        .setForceUpdate(true)
                                        // 更新日志
                                        .setUpdateLog(data.getChangelog())
                                        // 下载 url
                                        .setDownloadUrl(data.getInstallUrl())
                                        .create();
                            }
                            updateDialog.show();
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        LogUtils.e(e.getMessage());
                    }
                });
    }

    /**
     * 是否需要升级
     */
    private void getNeedAppUpdate() {
        EasyHttp.get(this)
                .api(new GetNeedUpdateApi())
                .request(new HttpCallback<HttpData<Void>>(this) {

                    @Override
                    public void onSucceed(HttpData<Void> data) {
                        if (null == updateDialog) {
                            updateDialog = new UpdateDialog.Builder(HomeActivity.this)
                                    // 版本名
                                    .setVersionName("梦驼铃司机帮")
                                    // 是否强制更新
                                    .setForceUpdate(true)
                                    // 更新日志
                                    .setUpdateLog("为了给您提供更优质的服务，请更新至最新版本")
                                    // 下载 url
                                    .setDownloadUrl(data.getMessage())
                                    .create();
                        }
                        updateDialog.show();
                    }

                    @Override
                    public void onFail(Exception e) {
                        LogUtils.e(e.getMessage());
                    }
                });
    }

}